import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export interface assembly {
  [x: string]: any;
  MemberId?: any;
  PartNumber?: any;
  SerialNumber?: any;
  SparePartNumber?: any;
  Model?: any;
  Name?: any;
  Location?: any;
  LocationIndicatorActive?: any;
}

export const useAssemblyStore = defineStore('AssemblyStore', () => {
  const assemblies = ref([] as assembly[]);
  const setAssemblyInfo = (data: assembly[]) => {
    assemblies.value = data.map((assembly: assembly) => {
      const {
        MemberId,
        PartNumber,
        SerialNumber,
        SparePartNumber,
        Model,
        Name,
        Location,
        LocationIndicatorActive,
      } = assembly;
      return {
        id: MemberId,
        partNumber: PartNumber,
        serialNumber: SerialNumber,
        sparePartNumber: SparePartNumber,
        model: Model,
        name: Name,
        locationNumber: Location?.PartLocation?.ServiceLabel,
        identifyLed: LocationIndicatorActive,
        uri: assembly['@odata.id'],
      };
    });
  };
  const getAssemblyInfo = async () => {
    return await api
      .get('/redfish/v1/Chassis/chassis/Assembly')
      .then(({ data }) => setAssemblyInfo(data?.Assemblies))
      .catch((error) => console.log(error));
  };
  const updateIdentifyLedValue = async (led: {
    uri: any;
    identifyLed: any;
  }) => {
    const uri = led.uri;
    const updatedIdentifyLedValue = {
      LocationIndicatorActive: led.identifyLed,
    };
    return await api.patch(uri, updatedIdentifyLedValue).catch((error) => {
      getAssemblyInfo();
      console.log('error', error);
      if (led.identifyLed) {
        throw new Error(
          t('pageInventory.toast.errorEnableIdentifyLed') as string,
        );
      } else {
        throw new Error(
          t('pageInventory.toast.errorDisableIdentifyLed') as string,
        );
      }
    });
  };

  return {
    assemblies,
    setAssemblyInfo,
    getAssemblyInfo,
    updateIdentifyLedValue,
  };
});
